package com.dc.juc.example._3_atomic;

import com.dc.juc.annoations.ThreadSafe;
import com.google.common.base.Throwables;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
import java.util.concurrent.atomic.AtomicLong;

/**
 * Description: 多线程场景下，使用 Atomic 完成变量的 ‘++’ 操作，保证线程安全
 * @author: gdc
 * @date: 2021/7/28
 * @version 1.0
 */
@ThreadSafe
@Slf4j
public class _2_AtomicLong {

    /**
     * 请求总数
     */
    public static int CLIENT_TOTAL = 5000;
    /**
     * 同时并发执行的线程数
     */
    public static int THREAD_TOTAL = 200;

    /**
     * 累加变量
     *  此处将 COUNT 计数，由int修改为 AtomicLong,是线程安全
     */
    public static AtomicLong COUNT = new AtomicLong(0);

    public static void main(String[] args) throws InterruptedException {
        ExecutorService threadPool = Executors.newCachedThreadPool();
        Semaphore semaphore = new Semaphore(THREAD_TOTAL);
        CountDownLatch countDownLatch = new CountDownLatch(CLIENT_TOTAL);


        for (int i = 0; i < CLIENT_TOTAL; i++) {
            threadPool.execute(() -> {
                try {
                    semaphore.acquire();

                    add();

                    semaphore.release();
                } catch (InterruptedException e) {
                    log.error("异常信息为：{}", Throwables.getStackTraceAsString(e));
                } finally {
                    countDownLatch.countDown();
                }
            });
        }

        countDownLatch.await();
        threadPool.shutdown();
        log.info("count:{}", COUNT);
    }

    /**
     * COUNT 计数 +1
     */
    private static void add() {
        COUNT.incrementAndGet();
    }
}
